package com.android.example.app3;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<String> currentData = new MutableLiveData<>();
    private final MutableLiveData<List<String>> itemList = new MutableLiveData<>();

    public void setData(String data) {
        currentData.setValue(data);
    }

    public LiveData<String> getCurrentData() {
        return currentData;
    }

    // 初始化数据
    public void SharedListViewModel() {
        List<String> initialList = new ArrayList<>();
        itemList.setValue(initialList);
    }

    public LiveData<List<String>> getItemList() {
        return itemList;
    }

    public void setItemList(List<String> newList) {
        itemList.setValue(newList);
    }

    public void addItem(int i, String item) {
        List<String> currentList = new ArrayList<>(Objects.requireNonNull(itemList.getValue()));
        currentList.add(i, item);
        itemList.setValue(currentList);
    }

    public void removeItemByName(String itemName) {
        List<String> currentList = new ArrayList<>(Objects.requireNonNull(itemList.getValue()));
        boolean removed = currentList.remove(itemName); // 移除第一个匹配项
        if (removed) {
            itemList.setValue(currentList);
        }
    }

}